package cn.sjx.graduate.service.impl;

import cn.sjx.graduate.constant.StaffCodeMsg;
import cn.sjx.graduate.domain.*;
import cn.sjx.graduate.exception.BusinessException;
import cn.sjx.graduate.mapper.StaffPayrollMapper;
import cn.sjx.graduate.qo.StaffTypeQuery;
import cn.sjx.graduate.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author bo-feifei
 * @since 2021-11-07
 */
@Service
public class StaffPayrollServiceImpl extends ServiceImpl<StaffPayrollMapper, StaffPayroll> implements IStaffPayrollService {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IStaffTypeService staffTypeService;
    @Autowired
    private IStaffService staffService;


    /**
     * 职工的工资是 部门工资（基础工资） + 职务工资 - 请假小时数*时薪
     * 时薪 = 职务工资/每月基本工作小时
     *
     * @param id
     */
    @Override
    @Transactional(rollbackForClassName = "Exception")
    public void payroll(Long id) {
        Staff staff = staffService.getById(id);
        Date payoffTime = staff.getPayoffTime();
        long timeDifference = 0;
        if(staff.getPayoffTime()!=null ){
            long time =payoffTime.getTime();
            long time1 = new Date().getTime();
             timeDifference = time1-time;
        }
        // 29天的时间戳  以29天来算一个月 不以30天来算 就是防止一些以外事情
        long monthTimestamp = 2505600000l;
        if (timeDifference < monthTimestamp) {//0会比这个小，这样就行了
            throw new BusinessException(StaffCodeMsg.PAYROLL_TRUE);
        }
        // 获取该教职工的员工编号以便知道其属于那个部门
        Long employeeId = staff.getEmployeeId();
        Employee employee = employeeService.getById(employeeId);
        // 获取当前员工所属的部门编号
        Integer deptId = employee.getDept();
        Department department = departmentService.getById(deptId);
        // 获取当前部门的基础工资
        BigDecimal departmentSalary = department.getBaseSalary();
        // 获取员工等级工资
        Integer type = staff.getType();
        StaffType staffType = staffTypeService.getById(type);
        // 职位工资
        BigDecimal staffSalary = staffType.getBaseSalary();
        String salaryStr = staffSalary.stripTrailingZeros().toPlainString();
        // 如果该职工的月基本工资量  得到相应的时薪
        String basicWorkload = staff.getBasicWorkload();
        // 时薪
        BigDecimal hoursSalary = staffSalary.divide(new BigDecimal(basicWorkload), 2, RoundingMode.HALF_UP)
                .setScale(2, RoundingMode.HALF_UP);
        // 获取请假时长
        Integer leaveHours = staff.getLeaveHours();
        // 请假一共扣除的工资
        BigDecimal leaveSalary = hoursSalary.multiply(new BigDecimal(String.valueOf(leaveHours)))
                .setScale(2, RoundingMode.HALF_UP);
        // 获取该员工的 加班工资总额
        Integer overTime = staff.getOverTime();
        BigDecimal timeSalary = hoursSalary.multiply(new BigDecimal(String.valueOf(overTime)))
                .setScale(2, RoundingMode.HALF_UP);
        // 总工资
        BigDecimal totalSalary = departmentSalary.add(staffSalary).add(timeSalary).subtract(leaveSalary);
        StaffPayroll staffPayroll = new StaffPayroll();
        BeanUtils.copyProperties(staff, staffPayroll);
        staffPayroll.setId(null);
        staffPayroll.setOvertimeWages(timeSalary);
        staffPayroll.setTotalWages(totalSalary);
        staffPayroll.setLeaveSalary(leaveSalary);
        staffPayroll.setBasicPay(departmentSalary.add(staffSalary).setScale(2, RoundingMode.HALF_UP));
        staffPayroll.setCreateTime(new Date());
        this.save(staffPayroll);
        // 清空当月教职员工的加班和请假时长
        staff.setLeaveHours(0);
        staff.setOverTime(0);
        staff.setPayoffTime(new Date());

        staffService.saveOrUpdate(staff);

    }

    @Override
    public IPage<StaffPayroll> queryPage(StaffTypeQuery qo, Employee employee) {
        Boolean admin = employee.getAdmin();
        IPage<StaffPayroll> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        QueryWrapper<StaffPayroll> wrapper = new QueryWrapper<>();
        if (!admin) {
            // 如果不是管理员 就只能查看自己的工资情况
            wrapper.eq("employee_id", employee.getId());
        }
        wrapper.orderByDesc("create_time");
        IPage<StaffPayroll> page1 = super.page(page, wrapper);
        List<StaffPayroll> records = page1.getRecords();
        int size = records.size();
        String s = String.valueOf(size);
        page1.setTotal(Long.parseLong(s));
        return page1;
    }


}
